package ikeypairs

import (
	"gitee.com/djaf/my-certs/app/classes/keypairs"
	"gitee.com/djaf/my-certs/app/data/dxo"
	"gitee.com/djaf/my-certs/app/data/entity"
	"github.com/starter-go/security/random"
	"gorm.io/gorm"
)

// KeyPairDaoImpl ...
type KeyPairDaoImpl struct {

	//starter:component

	_as func(keypairs.DAO) //starter:as("#")

	Agent       dxo.DatabaseAgent  //starter:inject("#")
	UUIDService random.UUIDService //starter:inject("#")

}

func (inst *KeyPairDaoImpl) _impl() keypairs.DAO {
	return inst
}

func (inst *KeyPairDaoImpl) model() *entity.KeyPair {
	return new(entity.KeyPair)
}

func (inst *KeyPairDaoImpl) modelList() []*entity.KeyPair {
	return make([]*entity.KeyPair, 0)
}

func (inst *KeyPairDaoImpl) makeResult(item *entity.KeyPair, res *gorm.DB) (*entity.KeyPair, error) {
	err := res.Error
	if err != nil {
		return nil, err
	}
	return item, nil
}

// Find ...
func (inst *KeyPairDaoImpl) Find(db *gorm.DB, id dxo.KeyPairID) (*entity.KeyPair, error) {
	m := inst.model()
	db = inst.Agent.DB(db)
	res := db.First(m, id)
	return inst.makeResult(m, res)
}

// List ...
func (inst *KeyPairDaoImpl) List(db *gorm.DB) ([]*entity.KeyPair, error) {
	list := inst.modelList()
	db = inst.Agent.DB(db)
	res := db.Find(&list)
	if res.Error != nil {
		return nil, res.Error
	}
	return list, nil
}

// Insert ...
func (inst *KeyPairDaoImpl) Insert(db *gorm.DB, item *entity.KeyPair) (*entity.KeyPair, error) {

	uuid := inst.UUIDService.Build().Class("entity.KeyPair").Generate()

	item.ID = 0
	item.UUID = uuid

	db = inst.Agent.DB(db)
	res := db.Create(item)
	return inst.makeResult(item, res)
}

// Update ...
func (inst *KeyPairDaoImpl) Update(db *gorm.DB, id dxo.KeyPairID, fn func(item *entity.KeyPair)) (*entity.KeyPair, error) {
	ent := inst.model()
	db = inst.Agent.DB(db)
	res := db.First(ent, id)
	if res.Error != nil {
		return nil, res.Error
	}
	fn(ent)
	res = db.Save(ent)
	return inst.makeResult(ent, res)
}

// Remove ...
func (inst *KeyPairDaoImpl) Remove(db *gorm.DB, id dxo.KeyPairID) error {
	m := inst.model()
	db = inst.Agent.DB(db)
	res := db.Delete(m, id)
	return res.Error
}
